package com.ywl.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ywl.common.CustomException;
import com.ywl.common.R;
import com.ywl.dto.HouseDetailDto;
import com.ywl.entity.HouseDetail;
import com.ywl.service.HouseDetailService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ywl
 * @since 2022-08-26
 */
@RestController
@Api(tags = "房屋相关接口")
public class HouseDetailController {

    @Autowired
    HouseDetailService houseDetailService;

    /**
     * 搜索接口
     * 分页查询，根据城市，内容进行查询
     * @param city
     * @param content
     * @param page    当前页数
     * @return
     */
    @ApiOperation("搜索接口")
    @GetMapping("/search")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "city",value = "房屋所在城市",required = true),
            @ApiImplicitParam(name = "content",value = "标题内容",required = true),
            @ApiImplicitParam(name = "page",value = "当前页号，从0开始",required = true)
    })
    public R<List<HouseDetail>> getPage(String city, @RequestParam(defaultValue = "") String content, Integer page) {
        Page<HouseDetail> houseDetailPage = new Page<HouseDetail>(page + 1, 5);
        houseDetailService.getPageByCondition(houseDetailPage, city, content);

        if (houseDetailPage == null) {
            throw new CustomException("请求失败");
        }

        int maxPage = (int) houseDetailPage.getPages();//总页数
        int currentPage = (int) houseDetailPage.getCurrent();//当前页数

        //如果当前页数和最大页数相等时，则代表没有下一页
        if (currentPage == maxPage) {
            return R.success(houseDetailPage.getRecords(), false);
        } else {
            return R.success(houseDetailPage.getRecords(), true);
        }
    }

    @ApiOperation("房屋详情接口")
    @GetMapping("/details")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "房屋id", required = true)
    })
    @Cacheable(value = "houseDetailCache",
            key = "'houseDetail_'+#id",
            unless = "#result != null"
    )
    public HouseDetailDto getDetails(Long id) {
        HouseDetailDto houseDetailDto = houseDetailService.getHouseDetailWithInfo(id);
        if(houseDetailDto == null){
            throw new CustomException("请求失败");
        }
        return houseDetailDto;
    }
}

